package model

import (
	"encoding/json"
	"fmt"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"gitee.com/zaiqiang231/lovesport-user-service/app/model/meta"
	"github.com/ory/ladon"
	"gorm.io/gorm"
)

type Policy struct {
	meta.RecordModel
	Name         string     `json:"name" validate:"required,name" gorm:"column:name;not null;"`
	UserName     string     `json:"username" validate:"omitempty"  gorm:"column:username;not null;"`
	PolicyShadow string     `json:"-" validate:"omitempty" gorm:"column:policy_shadow;"`
	Policy       AuthPolicy `json:"policy,omitempty" validate:"omitempty" gorm:"-"`
}

func (Policy) TableName() string {
	return "policy"
}

type AuthPolicy struct {
	ladon.DefaultPolicy
}

func (ap AuthPolicy) String() string {
	data, _ := json.Marshal(ap)
	return string(data)
}

func (p *Policy) BeforeCreate(tx *gorm.DB) error {
	baseLog.Debugf("Policy Before Create")
	p.Policy.ID = p.Name
	p.PolicyShadow = p.Policy.String()
	return nil
}

func (p *Policy) BeforeUpdate(tx *gorm.DB) error {
	baseLog.Debugf("Policy Before Update")
	p.Policy.ID = p.Name
	p.PolicyShadow = p.Policy.String()
	return nil
}

func (p *Policy) AfterFind(tx *gorm.DB) error {
	baseLog.Debugf("Policy After Find")
	if err := json.Unmarshal([]byte(p.PolicyShadow), &p.Policy); err != nil {
		return fmt.Errorf("failed to unmarshal policyShadow: %w", err)
	}
	return nil
}
